import {CProduct} from '../types/product'

interface CState{
    carList:CProduct[]
}

let initDate:CState = {
    carList:[]
}

let getIndex = (carList:CProduct[],id:number) => {
    return carList.findIndex((item:CProduct) => item.id === id)
}

export default (state=initDate,action:any) => {
    switch (action.type) {
        //添加购物车
        case 'ADD_CAR':
            //1.未添加购物车  2，已添加购物车
            let index = getIndex(state.carList,action.item.id);
             //从未添加
             
            if(index != -1){
                //已经添加过
                let target = state.carList[index];
                target.num++;
                state.carList[index] = {...target};
            }else{
                let target = action.item;
                //从未添加
                target.num = 1;
                target.checked = true;
                state.carList.push(target);
            }
            return {carList:[...state.carList]};
        //选中和补选中
        case 'CHANGE_CHECK':{
            let index = getIndex(state.carList,action.id);
            let target = state.carList[index];
            target.checked = action.checked;
            state.carList[index] = {...target};
            return {carList:[...state.carList]}
        }

        //初始购物车列表
        case 'INIT_LIST':{
            return {carList:[...action.list]}
        }
        default:
            return state;
    }
}